<?php
/**
 * 商品分类
 * Author: hades
 * DateTime: 2020/5/16 15:16
 */

namespace App\Controller\admin;

use App\Lib\Tree;
use App\Model\GCategory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * Class CategoryController
 * @package App\Controller\admin
 * @Controller(prefix="a/category")
 * @Middleware(\App\Middleware\AdminMiddleware::class)
 */
class CategoryController extends AdminBase {

    /**
     * 获取列表
     * @RequestMapping(path="lists",methods="get")
     * @return array
     */
    public function getLists() {
        $lists = GCategory::query()
            ->orderBy('sequence', 'desc')
            ->orderBy('id')
            ->select('id', 'parent_id', 'name')
            ->get()->toArray();
        $lists = Tree::makeTree($lists);
        return success(['lists' => $lists]);
    }

    /**
     * 添加、编辑
     * @RequestMapping(path="save",methods="post")
     * @return array
     */
    public function save() {
        $name = $this->body('name');
        $parent = $this->body('parent');
        $id = $this->body('id');
        if (empty($name) || empty($path)) {
            return error('参数错误');
        }
        $name = mb_substr($name, 0, 10);
        // 查询父级
        if ($parent) {
            $parentID = GCategory::query()
                ->where('id', $parent)
                ->value('parent_id');
            if ($parentID === null) {
                return error('父级不存在');
            }
            if ($parentID != 0) {
                return error('分类只能有两级');
            }
        }
        $data = ['name' => $name, 'parent_id' => $parent,];
        if ($id) {
            $r = GCategory::query()->where('id', $id)->update($data);
        } else {
            $r = GCategory::query()->insert($data);
        }
        return $r ? success() : error();
    }

    /**
     * 更新排序
     * @return array
     * @RequestMapping(path="sequence",methods="post")
     */
    public function postSequence() {
        $sort = $this->body('sort');
        $id = $this->body('id');
        $r = GCategory::query()
            ->where('id', $id)
            ->update(['sequence' => $sort]);
        return $r ? success() : error();
    }
}
